package com.angus.common.security.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import java.time.Duration;
import java.util.Properties;

/**
 * @author lineCode
 */
@Data
@ConfigurationProperties(prefix = "send-code")
public class SendCodeConfig {
    // 发送配置（send-code 前缀）
    private Duration expireTimes;
    private Duration sendFrequency;
    private Integer maxSendCount;
    private Integer beginCode;
    private Integer endCode;

    // 嵌套的邮件配置（对应 send-code.mail 前缀）
    private Mail mail;

    @Data
    public static class Mail {
        private String host;
        private int port;
        private String username;
        private String password;
        private Properties properties;
    }

    @Bean
    public JavaMailSender javaMailSender() {
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        // 从嵌套配置中获取邮件服务器信息
        mailSender.setHost(mail.getHost());
        mailSender.setPort(mail.getPort());
        mailSender.setUsername(mail.getUsername());
        mailSender.setPassword(mail.getPassword());
        // **关键修改：设置默认编码为UTF-8**
        mailSender.setDefaultEncoding("UTF-8");
        // 设置邮件属性（从配置中直接获取，无需手动设置）
        if (mail.getProperties() != null) {
            mailSender.setJavaMailProperties(mail.getProperties());
            // 确保Properties中包含编码设置
            if (mail.getProperties().get("mail.smtp.encoding") == null) {
                mail.getProperties().setProperty("mail.smtp.encoding", "UTF-8");
            }
        }
        return mailSender;
    }
}
